package com.ygl.framework.mvc;

import com.ygl.entity.User;
import com.ygl.framework.exception.MyException;
import com.ygl.framework.jwt.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ygl
 * @date 2021/7/8
 * @description 自定义拦截器
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtUtil.token);
        User user = JwtUtil.getUser(token);
        if (user == null) {
            throw new MyException("超时或者不合法");
        }
        // token延期,生成新的token
        String newToken = JwtUtil.sign(user);
        response.setHeader(JwtUtil.token, newToken);
        request.setAttribute("user", user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
